﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace SmoothStreaming.PerformanceTesting
{
    public class ChunkRetriever
    {
        Dictionary<string, string> _responseHeaders = new Dictionary<string, string>();
        public HttpStatusCode ReturnStatusCode { get; private set; }

        public Dictionary<string, string> ResponseHeaders { get { return _responseHeaders; } }

        public ChunkResponse DownloadChunkStatsOnly(SmoothStreamChunk chunk)
        {
            ChunkResponse cr = new ChunkResponse() { RequestedAt = DateTime.Now };
            try
            {
                var response = GetWebPageContent(chunk.ChunkUrl, 1000);
            }
            catch (WebException webEx)
            {
                using (WebResponse response = webEx.Response)
                {
                    ReturnStatusCode = (response as HttpWebResponse).StatusCode;
                } 
            }
            catch (Exception)
            {

            }
            cr.ResponseCompletedAt = DateTime.Now;

            cr.Headers = _responseHeaders;
            cr.ReturnStatusCode = ReturnStatusCode;

            return cr;
        }

        private byte[] GetWebPageContent(string url, int bytesToGet)
        {
            _responseHeaders = new Dictionary<string, string>();

            HttpWebRequest request;
            request = WebRequest.Create(url) as HttpWebRequest;

            //get first 1000 bytes
            request.AddRange(0, bytesToGet - 1);

            // the following code is alternative, you may implement the function after your needs
            using (WebResponse response = request.GetResponse())
            {
                foreach (var header in response.Headers.AllKeys)
                {
                    _responseHeaders[header] = response.Headers[header];
                }

                HttpWebResponse hwr = response as HttpWebResponse;
                ReturnStatusCode = hwr.StatusCode;

                using (Stream stream = response.GetResponseStream())
                {
                    byte[] buffer = new byte[bytesToGet];
                    int read = stream.Read(buffer, 0, bytesToGet);
                    Array.Resize(ref buffer, read);
                    return buffer;
                }
            }
        }
    }
}
